package com.newmuis.open.codeeval.easy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * CodeEval.com > Easy Challenges > Multiples of a Number
 * 
 * Description:
 * 
 * Given numbers x and n, where n is a power of 2, print out the smallest multiple of n which is
 * greater than or equal to x. Do not use division or modulo operator.
 * 
 * Input sample:
 * 
 * The first argument will be a text file containing a comma separated list of two integers, one
 * list per line. e.g.
 * 
 * 13,8
 * 17,16
 * 
 * Output sample:
 * 
 * Print to stdout, the smallest multiple of n which is greater than or equal to x, one per line.
 * e.g.
 * 
 * 16
 * 32
 * 
 * @author Jonathan Newmuis (jon@newmuis.com)
 * @category easy
 * 
 */
public class multiples {
	/**
	 * Prints out the smallest multiple of n that is greater than x to {@link System.out}.
	 * 
	 * @param x
	 * @param n
	 */
	private static void findSmallestMultiple(final int x, final int n) {
		int i = 0;

		// Determine which direction to iterate based on sign of x.
		if (x >= 0) {
			while (i * n < x) {
				i++;
			}
		} else {
			while (i * n > x) {
				i--;
			}
		}

		// Output the smallest multiple of n that is greater than x.
		System.out.println(i * n);
	}

	/**
	 * @param args should contain only one CLI argument: the path to an input file which specifies
	 *            the input in the defined format.
	 * @throws IOException if there is a problem reading the given input file.
	 */
	public static void main(final String[] args) throws IOException {
		// Verify input argument length.
		if (args.length < 1) {
			throw new RuntimeException("Must specify input file path.");
		} else if (args.length > 1) {
			throw new RuntimeException("Illegal input arguments specified.");
		}

		// Read file from specified path.
		final BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
		String line;

		while ((line = reader.readLine()) != null) {
			// Parse the arguments.
			final String[] multiplesArgs = line.split(",");

			// Verify the length of the "multiples" arguments given in the input file.
			if (multiplesArgs.length != 2) {
				throw new RuntimeException("Input file must contain two arguments per line.");
			}

			try {
				// Parse n and x from the input file.
				final int x = Integer.parseInt(multiplesArgs[0]);
				final int n = Integer.parseInt(multiplesArgs[1]);
				findSmallestMultiple(x, n);
			} catch (final NumberFormatException e) {
				throw new RuntimeException("Input file contained non-numeric arguments.");
			}
		}
	}
}
